/*
 * Created on Jul 7, 2005
 *
 */
package com.erclab.internal.xpresso.webapp;

import java.util.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.erclab.internal.xpresso.FormFactory;
import com.erclab.internal.xpresso.OptionsFactory;
import com.erclab.internal.xpresso.ReportFactory;
import com.erclab.internal.xpresso.Resource;
import com.erclab.internal.xpresso.XpressoConstants;
import com.erclab.internal.xpresso.exceptions.ReportException;
import com.erclab.internal.xpresso.forms.Form;
import com.erclab.internal.xpresso.forms.FormParameters;
import com.erclab.internal.xpresso.forms.FormResultSet;
import com.erclab.internal.xpresso.reports.Report;
import com.erclab.internal.xpresso.reports.ReportParameters;
import com.erclab.internal.xpresso.reports.ReportResultSet;
import com.erclab.internal.xpresso.reports.ReportView;
import com.erclab.internal.xpresso.security.User;
import com.erclab.internal.xpresso.webapp.servlets.WebUserManagement;
import com.xpresso.utils.exceptions.XpressoException;

/**
 * @author Enrique Rodriguez.
 *
 */
public class WebObjectFactory {

	protected static final Logger log = Logger.getLogger(WebObjectFactory.class);
	
	public static String createAndAddReport(HttpServletRequest request, 
											String reportName, 
											String uniqueKeyValue) throws SecurityException, Exception{
		log.info("The report: "+  reportName + " has been requested");
		HttpSession session = request.getSession();
		User user = WebUserManagement.loadUser(session, request);

		Report theReport = ReportFactory.loadReport(reportName);

		ReportParameters parameters = new ReportParameters();
		parameters.setPageNum(request.getParameter("pageNum"));
		parameters.setUniqueKeyValue(uniqueKeyValue);
		parameters.setSortColumn(request.getParameter("sortOrder"));
		parameters.setUser((User)session.getAttribute("user"));
		parameters.setExportFlag(request.getParameter("exportReport"));
		parameters.setRequestedView(request.getParameter("view"));

		HashMap<String, String[]> conditions = new HashMap<String, String[]>();
		HashMap<String, String> requestParameters  = new HashMap<String, String>();
		
		Enumeration enumeration = request.getParameterNames();
		while(enumeration.hasMoreElements()){
			String name = (String)enumeration.nextElement();
			if (name != null && name.indexOf("Filter") == 0){
				conditions.put(name, request.getParameterValues(name));	
			} else if (name != null && name.indexOf("Param") == 0){
				requestParameters.put(name, request.getParameter(name));			
			}
		}
		parameters.setConditions(conditions);
		parameters.setRequestParameters(requestParameters);		

		theReport.setReportParameters(parameters);

		// TODO log this for statistics purposes
		ReportResultSet rrs = ReportFactory.executeReportQuery(theReport);

		// Load Options
		OptionsFactory.loadReportOptions(theReport, (User)session.getAttribute("user"));

		//recordCurrentUrl(session, theReport, parameters);

		setViewParameters(request, theReport);
		
		request.setAttribute("Report", theReport);
		request.setAttribute("ReportResultSet", rrs);
		request.setAttribute("pageNum", new Integer(parameters.getPageNum()));
		
		return getViewHandler(theReport);
	}

	protected static String getViewHandler(Report theReport) throws XpressoException {
		String requestedView = theReport.getReportParameters().getRequestedView();
		if (requestedView != null){
			for(ReportView view:theReport.getReportViews()){
				if (view.getViewName().equals(requestedView)){
					return view.getViewPath();
				}
			}
		} else {
			return theReport.getViewHandler();
		}
		throw new XpressoException("View: " + requestedView + " not found", new Exception());
	}
	
	public static void setViewParameters(HttpServletRequest request, Resource resource) {
		if (resource.getViewParameters() == null) return;
		for (String key : resource.getViewParameters().keySet()) {
			request.setAttribute(key, resource.getViewParameters().get(key));
		}
	}

	public static String createAndAddReport(HttpServletRequest request, String reportName) throws SecurityException, Exception{
		return createAndAddReport(request, reportName, request.getParameter("uniqueKeyValue"));
	}
	
	public static String createAndAddForm(HttpServletRequest request, String formName) throws SecurityException, Exception{
		HttpSession session = request.getSession();		
		User user = WebUserManagement.loadUser(session, request);		
		
		Form theForm = FormFactory.loadForm(formName);

		FormParameters parameters = new FormParameters();
		parameters.setParentKeyValue(request.getParameter("parentKeyValue"));
		parameters.setUniqueKeyValue(request.getParameter("uniqueKeyValue"));
		parameters.setAction(extractFormAction(request));
		parameters.setUser((User)session.getAttribute("user"));

		setRequestParameters(request, parameters);
		
		theForm.setFormParameters(parameters);
		FormResultSet frs = FormFactory.createForm(theForm);

		// Load Options
		OptionsFactory.loadFormOptions(theForm, (User)session.getAttribute("user"));
		
		setViewParameters(request, theForm);
		
		request.setAttribute("Form", theForm);
		request.setAttribute("FormResultSet", frs);
		
		return theForm.getViewHandler();
	}

	protected static String extractFormAction(HttpServletRequest request) {
		String action = request.getParameter("action"); 
		if (action == null){
			return XpressoConstants.ACTION_INSERT;
		} else {
			return action;
		}
	}

	protected static void setRequestParameters(HttpServletRequest request, FormParameters parameters) {
		HashMap<String, String> requestParameters  = new HashMap<String, String>();
		
		Enumeration enumeration = request.getParameterNames();
		while(enumeration.hasMoreElements()){
			String name = (String)enumeration.nextElement();
			requestParameters.put(name, request.getParameter(name));			
		}
		parameters.setRequestParameters(requestParameters);
	}

	/**
	 * @param req
	 * @param string
	 * @return
	 */
	public static String createAndAddFilter(HttpServletRequest request, String reportName) throws ServletException, ReportException, Exception {
		HttpSession session = request.getSession();
		User user = WebUserManagement.loadUser(session, request);

		Report theReport = ReportFactory.loadReport(reportName);
		// Load Options
		OptionsFactory.loadReportOptions(theReport, (User)session.getAttribute("user"));

		request.setAttribute("Report", theReport);

		return theReport.getFilterViewHandler();
	}
	
	

	/**
	 * @param session
	 */
	/*private static void recordCurrentUrl(HttpSession session, Report theReport, ReportParameters parameters) {
		// Store the current url into a session to know where to come back if the user go to another page
		StringBuffer sb = new StringBuffer();
		sb.append(theReport.getReportName() + ".report");
		sb.append("?");
		sb.append("uniqueKeyValue=" + parameters.getUniqueKeyValue());
		sb.append("&parentKeyValue=" + parameters.getParentKeyValue());
		sb.append("&conditions=" + parameters.getUrlConditons());
		
		session.setAttribute("forwardUrl", sb.toString());			
	}*/

}
